// 导入数据库操作模块
const db = require('../db/index')



// 获取订单票价处理函数
exports.getOrder = (req, res) => {
  let pagesize = 5
  let pagenum = (req.query.pagenum - 1)*pagesize
  const sql = `select id,area,city,sale_view,b.types as 'types',discount,price,(select count(1) from sale_order) as 'total'
  from sale_order a ,sale_types b
  where a.tid = b.tid
  ORDER BY id ASC
  limit ${pagenum},${pagesize}`
  db.query(sql,(err, results) => {
    if(err) return res.cc(err)
    if(results.length < 0) return res.cc('获取票价信息失败！')
    res.send({
      status: 0,
      message: '获取票价信息成功！',
      data: results,
      total: results[0].total
    })
  })
}

// 添加订单票价信息
exports.addOrder = (req, res) => {
  // 票价类型判断
  let p = req.body
  let ttid = 0
  if(p.types === '老年票'){
    ttid = 2001
  }else if(p.types === '学生票'){
    ttid = 2002
  }else if(p.types === '成人票'){
    ttid = 2003
  }else if(p.types === '团购票'){
    ttid = 2004
  }else{
    ttid = 2003
  }
  const sql = `insert into sale_order set area=?,city=?,sale_view=?,tid=${ttid},discount=?,price=?`
  db.query(sql, [req.body.area, req.body.city, req.body.sale_view, req.body.discount, req.body.price],(err, results) => {
    if(err) return res.cc(err)
    if(results.affectedRows !== 1) return res.cc('添加信息失败！')
    res.cc('添加信息成功！', 0)
  })
}

// 更新订单票价信息
exports.updateOrder = (req, res) => {
  // 票价类型判断
  let p = req.body
  let ttid = 0
  if(p.types === '老年票'){
    ttid = 2001
  }else if(p.types === '学生票'){
    ttid = 2002
  }else if(p.types === '成人票'){
    ttid = 2003
  }else if(p.types === '团购票'){
    ttid = 2004
  }else{
    ttid = 2003
  }
  const sql = `update sale_order set area=?,city=?,sale_view=?,tid=${ttid},discount=?,price=? where id =?`
  db.query(sql, [req.body.area, req.body.city, req.body.sale_view, req.body.discount, req.body.price ,req.body.id], (err, results) => {
    if(err) return res.cc(err)
    if(results.affectedRows !== 1) return res.cc('更新信息失败！')
    res.cc('更新信息成功！', 0)
  })
}

// 根据id删除信息
exports.deleteById = (req, res) => {
  const sql = `delete from sale_order where id =?`
  db.query(sql, req.params.id, (err, results) => {
    if(err) return res.cc(err)
    if(results.affectedRows !== 1) return res.cc('删除信息失败！')
    res.cc('删除信息成功！', 0)
  })
}